package com.tcse.ppmethodhandler.service;

import com.tcse.ppmethodhandler.entity.HttpTrace;
import com.tcse.ppmethodhandler.entity.SpanRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.logging.Logger;

@Slf4j
@Service
public class CollectService {
    
    public static HashMap<String, HashMap<Long, HttpTrace>> testSpanIdTraceMap = new HashMap<String, HashMap<Long, HttpTrace>>();
    
    public void addTrace(HttpTrace trace){
        if(trace.getTest() == null)
            return;
        
        HashMap<Long, HttpTrace> SpanIdTraceMap =  CollectService.testSpanIdTraceMap.get(trace.getTest());
        if(SpanIdTraceMap != null){
            HttpTrace traceRecordInMap = SpanIdTraceMap.get(trace.getSpanId());
            if(traceRecordInMap != null) {
                // 更新record
                List<SpanRecord> newTraceRecord = trace.getRecords();
                for (SpanRecord record : newTraceRecord) {
                    traceRecordInMap.getRecords().add(record);
                }
                // 更新uri/httpInfo
                if(traceRecordInMap.getHttpInfo() == null){
                    traceRecordInMap.setHttpInfo(trace.getHttpInfo());
                }
            }else{
                SpanIdTraceMap.put(trace.getSpanId(), trace);
            }
            
        }else{
            testSpanIdTraceMap.put(trace.getTest(), new HashMap<Long, HttpTrace>());
            testSpanIdTraceMap.get(trace.getTest()).put(trace.getSpanId(), trace);
        }
    }
    
    public static void sortSpan(){
        for (HashMap<Long, HttpTrace> SpanIdTraceMap : testSpanIdTraceMap.values()) {
            for(HttpTrace trace: SpanIdTraceMap.values()){
                if(trace.getRecords().size() != 0){
                    Collections.sort(trace.getRecords(), new Comparator<SpanRecord>() {
        
                        @Override
                        public int compare(SpanRecord o1, SpanRecord o2) {
                            // 升序
                            if(o1 == null)
                                return 1;
                            if(o2 == null)
                                return -1;
                            return o1.getSequence()-o2.getSequence();
                        }
                    });
                }
            }
        }
    }
    
    
    public static void writeFile()  {
        File file =new File("methodInvoke.log");
        try {
            if(!file.exists()){
                file.createNewFile();
            }
    
            
            FileWriter fileWritter = new FileWriter(file.getName(),true);
            fileWritter.write(String.valueOf(CollectService.testSpanIdTraceMap));
            fileWritter.close();
        }catch (IOException e){
            log.warn("FILE WRITE ERROR");
        }
        
        
    }

}
